import axios from "axios";
import router from "../router/index.js";
import { Toast } from "vant";
import storageHelper from "./storageHelper";
const baseJmpConfig = window.appConfig;
//默认值
if (process.env.NODE_ENV === "development") {
    // axios.defaults.baseURL = '';
    axios.defaults.baseURL = "http://jmp.tuoshecx.com/api";
} else {
    // axios.defaults.baseURL = "http://jmp.tuoshecx.com/api";
    axios.defaults.baseURL = baseJmpConfig.baseURL;
}
axios.defaults.headers.post["Content-Type"] = "application/json"; //application/x-www-form-urlencoded
axios.defaults.timeout = 60000;
//请求拦截器
axios.interceptors.request.use(
    (config) => {
        if (config.data instanceof FormData) {
            config.headers = {
                "Content-Type": "multipart/form-data"
            };
        } else {
            config.data = JSON.stringify(config.data);
            config.headers = {
                "Content-Type": "application/json"
            };
        }
        Toast.loading({
            message: "加载中...",
            forbidClick: true
        });
        config.headers.Authorization = "Bearer " + storageHelper.get("jmp_client_token");
        return config;
    },
    (error) => {
        Toast.fail("请求超时");
        return Promise.reject(error);
    }
);
//响应拦截器
axios.interceptors.response.use(
    (res) => {
        Toast.clear();
        let resData = res.data;
        if (res.status === 200) {
            if (resData.code == 0 || resData.code == 102 || resData.code == 103) {
                return resData;
            } else {
                Toast.fail(resData.messages[0]);
                return;
            }
        } else {
            Toast.fail(resData.messages[0]);
            router.push("/");
            return;
        }
    },
    (error) => {
        Toast.clear();
        if (!error.response) {
            Toast.fail("您的网络断掉了!");
        }
        if (error.response.status == 504 || error.response.status == 404) {
            Toast.fail("安全验证过期，请重新登陆!");
        } else if (error.response.status == 403) {
            Toast.fail("安全验证过期，请重新登陆!");
            router.push("/");
        } else {
            Toast.fail("发生错误!");
        }
        return Promise.reject(error);
    }
);
export default axios;
